package indi.kane.simpleproject.intercepter;

import indi.kane.simpleproject.entity.Account;
import indi.kane.simpleproject.service.impl.AccountService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName: LoginInterceptor
 * @Author: kane
 * @Date: 2019-11-07 4:10 下午
 * @Description:
 */
//@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);

    @Autowired
    private AccountService accountService;

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI().toString();
        logger.info(uri);
        String token = request.getHeader("h-token");
        if(token == null){
            logger.error("no token error.");
            throw new Exception("没有token");
        }

        Account account = accountService.selectByPrimaryKey(Long.valueOf(token));
        if(account == null){
            logger.error("not login, token:{}",token);
            throw new Exception("没有登录");
        }

        request.setAttribute("account",account);
        return true;
    }
}